package com.jwcao.common.cast.operation.access.field.collection;

import com.jwcao.common.cast.annotation.CastField;
import com.jwcao.common.cast.operation.CastFlow;
import com.jwcao.common.scan.object.ScanField;
import java.util.Collection;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;

/**
 * name: RecursionListAccessOperation description: TODO
 *
 * @author caojingwei date: 2023/3/24 14:49
 */
public class RecursionListAccessOperation extends ListFieldAccessOperation {

    private final CastFlow castFlow;

    public RecursionListAccessOperation(CastField castField, ScanField sourceField,
        ScanField targetField, Class sourceItemClass, Class targetItemClass,CastFlow castFlow) {
        super(castField, sourceField, targetField, sourceItemClass, targetItemClass);
        this.castFlow = castFlow;
    }

    @Override
    public Object execute(Object sourceObject) {
        Collection sourceCollection = (Collection) sourceField.get(sourceObject);

        if (CollectionUtils.isEmpty(sourceCollection)) {
            return sourceCollection;
        }

        return sourceCollection.stream().map(castFlow::execute).collect(Collectors.toList());
    }
}
